package master;

import javax.swing.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 不同的二叉搜索树2
 *
 * @author chenyw
 * @date 2022/7/31 10:24
 */
public class M95generateTrees {
    //分治法，利用特点，左子树都比自己小右子树都比自己打，可以划分两部分进行递归
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new LinkedList<TreeNode>();
        }
        return dfs(1, n);
    }

    private List<TreeNode> dfs(int start, int end) {
        LinkedList<TreeNode> list = new LinkedList<>();
        if (start > end) {
            list.add(null);
            return list;
        }
        for (int i = start; i <= end; i++) {
            //递归构建左子树
            List<TreeNode> leftNodes = dfs(start, i - 1);
            //递归构建右子树
            List<TreeNode> rightNodes = dfs(i + 1, end);
            //从左右子树集合里组合左右节点
            for (TreeNode left : leftNodes) {
                for (TreeNode right : rightNodes) {
                    TreeNode node = new TreeNode(i);
                    node.left = left;
                    node.right = right;
                    list.add(node);
                }
            }
        }
        return list;
    }


}
